package cn.ygh.bbo.system.web.controller;

import cn.ygh.bbo.common.annotation.Log;
import cn.ygh.bbo.common.annotation.OperationType;
import cn.ygh.bbo.framerwork.core.ResultAjax;
import cn.ygh.bbo.common.exception.TipException;
import cn.ygh.bbo.system.bean.Admin;
import cn.ygh.bbo.system.bean.Permission;
import cn.ygh.bbo.system.bean.RolePermission;
import cn.ygh.bbo.system.sdk.shiro.ShiroUtils;
import cn.ygh.bbo.system.service.PermissionService;
import cn.ygh.bbo.system.service.RolePermissionService;
import cn.ygh.bbo.system.utils.PermissionUtils;
import cn.ygh.bbo.system.web.utils.ConvertUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.*;

/**
 * 描述：权限  RestPageController
 * @author ygh
 */
@Controller
@RequestMapping("/restpage/permission")
public class PermissionController {

    private final Logger logger= LoggerFactory.getLogger(getClass());

    @Autowired
    PermissionService permissionService;

    @Autowired
    RolePermissionService rolePermissionService;

    /**
     * 判断是否循环引用
     * @param request 请求
     * @param response 响应
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/check",method = RequestMethod.GET)
    public ResultAjax check(HttpServletRequest request, HttpServletResponse response, Integer pid, Integer id){
        if (pid.equals(id)){
            throw new TipException("禁止循环引用");
        }
        List<Permission>permissions=permissionService.listfindByParentId(pid);
        Permission permission=permissions.stream().filter(e->e.getId().equals(id)).findFirst().orElse(null);
        if (permission!=null){
            throw new TipException("禁止循环引用");
        }
        return ResultAjax.success(true);
    }

    /**
     * 权限树
     * @param request 请求
     * @param response 响应
     * @return
     */
    @RequiresPermissions("system:permission:query")
    @ResponseBody
    @RequestMapping(value = "/queryTree",method = RequestMethod.GET)
    public List<Permission> grid(HttpServletRequest request, HttpServletResponse response, Permission search){
        List<Permission>permissions=permissionService.listfind(search, null);
        return ConvertUtils.listToTree(permissions);
    }

    /**
     * 管理员菜单导航获取
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryMenusTree",method = RequestMethod.GET)
    public List<Permission> queryMenus(HttpServletRequest request, HttpServletResponse response){
        Admin admin=ShiroUtils.getPrincipal();
        if (PermissionUtils.isAdmin(admin.getRoles())){
            return ConvertUtils.listToTree(permissionService.listfindMenusAll());
        }
        return ConvertUtils.listToTree(permissionService.listfindMenusByRoles(admin.getRoles()));
    }

    /**
     * 用户所有的权限
     * @param request 请求
     * @param response 响应
     * @return
     */
    @RequiresPermissions("system:role:query")
    @ResponseBody
    @RequestMapping(value = "/queryPermissionTreeByRoleId",method = RequestMethod.GET)
    public Map<String,Object> queryPermissionTreeByRoleId(HttpServletRequest request, HttpServletResponse response
            , Permission search, Integer roleId){
        Map<String,Object>result=new HashMap<>();
        List<Permission>permissions=permissionService.listfind(search,null);
        result.put("permissions", ConvertUtils.listToTree(permissions));
        //角色所拥有的权限
        List<RolePermission>rolePermissions=rolePermissionService.listfindByRoleIds(Arrays.asList(roleId));
        List<Integer>checked=new ArrayList<>();
        for (RolePermission rolePermission:rolePermissions){
            Permission permission=permissions.stream()
                    .filter(e->e.getId().equals(rolePermission.getPermissionId())).findFirst().get();
            if (permission.getType()==5){
                checked.add(rolePermission.getPermissionId());
            }

        }
        result.put("checked",checked);
        return result;
    }

    /**
     * 用户所有的权限
     * @param request 请求
     * @param response 响应
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryPermissions",method = RequestMethod.GET)
    public List<String> queryPermissions(HttpServletRequest request, HttpServletResponse response){
        Admin admin=ShiroUtils.getPrincipal();
        if (PermissionUtils.isAdmin(admin.getRoles())){
            return Collections.singletonList("*:*:*");
        }
        List<Permission>permissions=permissionService.listfindByRoles(admin.getRoles());
        List<String>result=new ArrayList<>();
        for (Permission permission:permissions){
            if (StringUtils.isNotBlank(permission.getPerms())){
                String[]perms=permission.getPerms().split(",");
                Collections.addAll(result, perms);
            }
        }
        return result;
    }

    /**
     * 详细
     * @param id
     * @return
     */
    @RequiresPermissions("system:permission:show")
    @ResponseBody
    @RequestMapping(value = "/get",method = RequestMethod.GET)
    public Permission get(HttpServletRequest request, HttpServletResponse response, Integer id){
        Permission result=permissionService.getById(id);
        return result;
    }


    /**
     * 创建数据api
     * @param request 请求
     * @param response 响应
     * @param obj 创建对象
     * @param errors 验证异常
     * @return
     */
    @Log(value="Permission",operationId=OperationType.CREATE)
    @RequiresPermissions("system:permission:create")
    @ResponseBody
    @RequestMapping(value = "/create",method = RequestMethod.POST)
    public ResultAjax create(HttpServletRequest request, HttpServletResponse response, @Valid Permission obj, BindingResult errors){
        if (errors.hasErrors()){
            FieldError err0=(FieldError)errors.getAllErrors().get(0);
            return ResultAjax.fail("添加失败！"+err0.getField()+":"+err0.getDefaultMessage());
        }
        permissionService.save(obj);
        return ResultAjax.success(obj);
    }

    /**
     * 更新数据api
     * @param request 请求
     * @param response 响应
     * @param obj 更新对象
     * @param errors 验证异常
     * @return
     */
    @Log(value="Permission",operationId=OperationType.UPDATE)
    @RequiresPermissions("system:permission:update")
    @ResponseBody
    @RequestMapping(value = "/update",method = RequestMethod.POST)
    public ResultAjax update(HttpServletRequest request, HttpServletResponse response, @Valid Permission obj, BindingResult errors){
        if (errors.hasErrors()){
            FieldError err0=(FieldError)errors.getAllErrors().get(0);
            return ResultAjax.fail("更新失败！"+err0.getField()+":"+err0.getDefaultMessage());
        }
        permissionService.update(obj);
        return ResultAjax.success(obj);
    }

    /**
     * 根据Ids删除
     * @param request 请求
     * @param response 响应
     * @param ids
     * @return
     */
    @Log(value="Permission",operationId=OperationType.DEL)
    @RequiresPermissions("system:permission:del")
    @ResponseBody
    @RequestMapping(value = "/del",method = RequestMethod.POST)
    public ResultAjax del(HttpServletRequest request, HttpServletResponse response, String ids){
        if (StringUtils.isBlank(ids)){
            return ResultAjax.fail("ids不能为空");
        }
        String[] idList=ids.split(",");
        permissionService.deleteByIds(idList);
        return ResultAjax.success();
    }

}
